<?php 

/* =======================
	ACTION SELECTION
======================= */
$type = $_GET["type"];

if ($type == "new")
{
	add_new_question($_POST["question"], $_POST["answers"]);
}
else if ($type == "results")
{
	enable_results($_GET["enable"]);
}
else if ($type == "get_question")
{
	//echo "pseudo get_question";
	get_question();
}
else if ($type == "vote")
{
	vote($_POST["question"], $_POST["answer"], $_POST["device_id"]);
}
else if ($type == "get_results")
{
	get_results();
}


/* ================
	GENERAL TOOLS
================ */

function login($url, $db_name, $user, $password)
{
	$con = mysql_connect($url, $user, $password);

	if (!$con)
		die('Could not connect: ' . mysql_error());
	mysql_select_db($db_name) or die("Could not select database: " . mysql_error());
	return $con;
}

function logout($con)
{
	mysql_close($con);
}

function last_question_id()
{
	$con = login_default();

	$TABLE_QUESTIONS = "vote_questions";
	$id_result =  mysql_query("SELECT MAX(id) as id FROM $TABLE_QUESTIONS");
	$id_obj = mysql_fetch_object($id_result);
	return $id_obj->id;

	logout($con);
}

/* ====================
	PROJECT SPECIFIC
==================== */

$TABLE_QUESTIONS = "vote_questions";
$TABLE_VOTES = "vote_votes";

function login_default()
{	
	$DB_URL = "";
	$DB_NAME = "";
	$USER_NAME = "";
	$PASS = "";

	return login($DB_URL, $DB_NAME, $USER_NAME, $PASS);
}

function add_new_question($question, $answers)
{
	$TABLE_QUESTIONS = "vote_questions";
	$con = login_default();

	$result = mysql_query("INSERT INTO $TABLE_QUESTIONS (question, answers) VALUES ('$question', '$answers')")
		or die("Error(add_new_question): " + mysql_error());

	echo "success";

	logout($con);
}

function enable_results($enable)
{
	$TABLE_QUESTIONS = "vote_questions";
	$con = login_default();

	$show = ($enable == "true") ? 1 : 0;
	$id = last_question_id();

	//echo "id: " . $id . ", enable: " . $show;

	$result = mysql_query("UPDATE $TABLE_QUESTIONS SET show_results = $show WHERE id = $id")
		or die("Error(enable_results): " + mysql_error());

	echo "success";

	logout($con);
}

function get_question()
{
	$TABLE_QUESTIONS = "vote_questions";
	$con = login_default();

	$id = last_question_id();
	$result = mysql_query("SELECT question, answers FROM $TABLE_QUESTIONS WHERE id = $id");
	$question = mysql_fetch_array($result);

	$json = '{';
	$json .= '"question": "' . $question['question'] . '", ';
	$json .= '"answers": "' . $question['answers'] . '"';
	$json .= '}';

	echo $json;

	logout($con);
}

function vote($question, $answer, $device_id)
{
	$TABLE_QUESTIONS = "vote_questions";
	$TABLE_VOTES = "vote_votes";
	$con = login_default();

	$last_id = last_question_id();
	$result = mysql_query("SELECT id, answers, show_results FROM $TABLE_QUESTIONS WHERE question = '$question'");
	$q = mysql_fetch_object($result);

	// check if voting is in progress
	if ($q->id != $last_id || $q->show_results == 1)
	{
		echo "Error:1"; // Voting ended
		return;
	}

	// check if answers contains current answer
	if (strpos($q->answers, $answer) === false)
	{
		echo "Error:2"; // Wrong answer submitted
		return;
	}

	// check if user not yet voted in this poll
	$result = mysql_query("SELECT id FROM $TABLE_VOTES WHERE device_id = '$device_id' AND question_id = $q->id");
	if (mysql_num_rows($result) > 0)
	{
		echo "Error:3"; // User already voted
		return;
	}

	// if all checks succeed - insert vote into DB
	$result = mysql_query("INSERT INTO $TABLE_VOTES (question_id, device_id, answer) VALUES ($q->id, '$device_id', '$answer')")
		or die ("Error: " + mysql_error());

	echo "success";

	logout($con);
}

function get_results()
{
	$TABLE_QUESTIONS = "vote_questions";
	$TABLE_VOTES = "vote_votes";
	$con = login_default();

	// Get last id where results are turned on
	$result =  mysql_query("SELECT MAX(id) as id FROM $TABLE_QUESTIONS WHERE show_results = 1");
	$id_obj = mysql_fetch_object($result);

	$result = mysql_query("SELECT question FROM $TABLE_QUESTIONS WHERE id = $id_obj->id");
	$question = mysql_fetch_object($result);
	//return $id_obj->id;
	// $id_obj->question;

	// info from DB about votes: 
	// question, answer list, count of distinct answers, count of all answers
	$result = mysql_query("SELECT count(*) as count FROM $TABLE_VOTES WHERE question_id = $id_obj->id");
	$count_obj = mysql_fetch_object($result);
	$count = $count_obj->count;

	// Get answers and their count for last endled question
	$result = mysql_query("SELECT answer, count(*) as count FROM $TABLE_VOTES WHERE question_id = $id_obj->id GROUP BY answer");
	//$answers = mysql_fetch_object($result);

	$json = '{';
	$json .= '"question" : "' . $question->question . '", ';
	$json .= '"total_count" : "' . $count . '", ';
	$json .= '"answers": [';

	$isEmpty = true;
	while ($answer = mysql_fetch_array($result))
	{
		$json .= '{ "answer" : "' . $answer["answer"] . '", "count" : "' . $answer["count"] . '" },';
		$isEmpty = false;
	}

	if (!$isEmpty)
		$json = substr($json, 0, -1);

	$json .= ']}';
	echo $json;

	logout($con);

	/* JSON example:
	{
	    "question": "why?",
	    "total_count": "15",
	    "answers": 
	    [
	        { "answer": "a", "count": "12" },
	        { "answer": "b", "count": "3" },
	        { "answer": "c", "count": "0" }
	    ]
	}
	*/
}


?>